package com.zhengbing.tj.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.ApiResponse;
import com.zhengbing.tj.common.ApiResult;
import com.zhengbing.tj.entity.Permission;
import com.zhengbing.tj.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

/**
 * 权限管理控制器
 * 处理权限相关的REST请求
 *
 * @author zhengbing
 * @date 2024-08-22
 */
@Api(tags = "权限管理", description = "提供权限的增删改查及角色权限关联等功能")
@RestController
@RequestMapping("/api/permissions")
public class PermissionController {
    
    @Autowired
    private PermissionService permissionService;
    
    /**
     * 获取所有权限
     * 查询系统中的所有权限信息
     *
     * @return 权限列表
     */
    @ApiOperation(value = "获取所有权限", notes = "查询系统中的所有权限信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功", response = Permission.class, responseContainer = "List")
    })
    @GetMapping
    public ApiResult<List<Permission>> getAllPermissions() {
        return ApiResult.success(permissionService.list());
    }
    
    /**
     * 根据ID获取权限
     * 根据权限ID查询权限详情
     *
     * @param id 权限ID
     * @return 权限信息
     */
    @ApiOperation(value = "根据ID获取权限", notes = "根据权限ID查询权限详情")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功", response = Permission.class),
        @ApiResponse(code = 404, message = "权限不存在")
    })
    @GetMapping("/{id}")
    public ApiResult<Permission> getPermissionById(@ApiParam(value = "权限ID", required = true, example = "1") @PathVariable Long id) {
        Permission permission = permissionService.getById(id);
        if (permission != null) {
            return ApiResult.success(permission);
        } else {
            return ApiResult.error(404, "权限不存在");
        }
    }
    
    /**
     * 添加权限
     * 创建新权限
     *
     * @param permission 权限信息
     * @return 添加结果
     */
    @ApiOperation(value = "添加权限", notes = "创建新权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "添加成功")
    })
    @PostMapping
    public ApiResult<String> addPermission(@ApiParam(value = "权限信息", required = true) @RequestBody Permission permission) {
        permissionService.save(permission);
        return ApiResult.success("添加成功", null);
    }
    
    /**
     * 更新权限
     * 根据ID更新权限信息
     *
     * @param id 权限ID
     * @param permission 权限信息
     * @return 更新结果
     */
    @ApiOperation(value = "更新权限", notes = "根据ID更新权限信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "更新成功"),
        @ApiResponse(code = 404, message = "权限不存在")
    })
    @PutMapping("/{id}")
    public ApiResult<String> updatePermission(@ApiParam(value = "权限ID", required = true, example = "1") @PathVariable Long id, @ApiParam(value = "权限信息", required = true) @RequestBody Permission permission) {
        Permission existing = permissionService.getById(id);
        if (existing == null) {
            return ApiResult.error(404, "权限不存在");
        }
        permission.setId(id);
        permissionService.updateById(permission);
        return ApiResult.success("更新成功", null);
    }
    
    /**
     * 删除权限
     * 根据ID删除权限
     *
     * @param id 权限ID
     * @return 删除结果
     */
    @ApiOperation(value = "删除权限", notes = "根据ID删除权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "删除成功")
    })
    @DeleteMapping("/{id}")
    public ApiResult<String> deletePermission(@ApiParam(value = "权限ID", required = true, example = "1") @PathVariable Long id) {
        permissionService.removeById(id);
        return ApiResult.success("删除成功", null);
    }
    
    /**
     * 批量删除权限
     * 根据ID列表删除多个权限
     *
     * @param ids 权限ID列表
     * @return 删除结果
     */
    @ApiOperation(value = "批量删除权限", notes = "根据ID列表删除多个权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "删除成功")
    })
    @DeleteMapping("/batch")
    public ApiResult<String> deletePermissions(@ApiParam(value = "权限ID列表", required = true) @RequestBody List<Long> ids) {
        permissionService.removeByIds(ids);
        return ApiResult.success("删除成功", null);
    }
    
    /**
     * 根据用户ID查询权限列表
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @ApiOperation(value = "根据用户ID查询权限列表", notes = "查询指定用户拥有的权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功", response = Permission.class, responseContainer = "List")
    })
    @GetMapping("/user/{userId}")
    public ApiResult<List<Permission>> getPermissionsByUserId(@ApiParam(value = "用户ID", required = true, example = "1") @PathVariable Long userId) {
        return ApiResult.success(permissionService.getPermissionsByUserId(userId));
    }
    
    /**
     * 根据角色ID查询权限列表
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @ApiOperation(value = "根据角色ID查询权限列表", notes = "查询指定角色拥有的权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功", response = Permission.class, responseContainer = "List")
    })
    @GetMapping("/role/{roleId}")
    public ApiResult<List<Permission>> getPermissionsByRoleId(@ApiParam(value = "角色ID", required = true, example = "1") @PathVariable Long roleId) {
        return ApiResult.success(permissionService.getPermissionsByRoleId(roleId));
    }
    
    /**
     * 分配角色权限
     * 为指定角色分配权限
     *
     * @param roleId 角色ID
     * @param permissionIds 权限ID列表
     * @return 分配结果
     */
    @ApiOperation(value = "分配角色权限", notes = "为指定角色分配权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "分配成功")
    })
    @PostMapping("/role/{roleId}/assign")
    public ApiResult<String> assignRolePermissions(@ApiParam(value = "角色ID", required = true, example = "1") @PathVariable Long roleId, @ApiParam(value = "权限ID列表", required = true) @RequestBody List<Long> permissionIds) {
        permissionService.saveRolePermissions(roleId, permissionIds);
        return ApiResult.success("分配成功", null);
    }
    
    /**
     * 检查用户权限
     * 检查指定用户是否拥有特定权限
     *
     * @param userId 用户ID
     * @param permissionCode 权限标识
     * @return 检查结果
     */
    @ApiOperation(value = "检查用户权限", notes = "检查指定用户是否拥有特定权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "检查成功", response = Boolean.class)
    })
    @GetMapping("/check")
    public ApiResult<Boolean> checkPermission(@ApiParam(value = "用户ID", required = true, example = "1") @RequestParam Long userId, 
                                            @ApiParam(value = "权限标识", required = true, example = "user:list") @RequestParam String permissionCode) {
        boolean hasPermission = permissionService.hasPermission(userId, permissionCode);
        return ApiResult.success(hasPermission);
    }
    
    /**
     * 根据token获取当前用户权限
     * 从请求头中获取token，解析后返回当前用户拥有的所有权限
     *
     * @param request HTTP请求对象
     * @return 用户权限列表
     */
    @ApiOperation(value = "根据token获取当前用户权限", notes = "从请求头中获取token，解析后返回当前用户拥有的所有权限")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功", response = Permission.class, responseContainer = "List"),
        @ApiResponse(code = 401, message = "未授权或token无效")
    })
    @GetMapping("/current-user")
    public ApiResult<List<Permission>> getCurrentUserPermissions(HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String authHeader = request.getHeader("Authorization");
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ApiResult.error(401, "未授权访问，token不存在或格式错误");
            }
            
            // 提取token值
            String token = authHeader.replace("Bearer ", "");
            
            // 调用服务层方法获取用户权限
            List<Permission> permissions = permissionService.getPermissionsByToken(token);
            return ApiResult.success(permissions);
        } catch (IllegalArgumentException e) {
            // token无效或用户不存在的情况
            return ApiResult.error(401, e.getMessage());
        } catch (Exception e) {
            // 其他异常
            return ApiResult.error(401, "获取权限失败：" + e.getMessage());
        }
    }
}